import type { Module } from "vuex"
import type { ILoginState, IAccout } from "./types"
import type { IRootState } from "../types"

import { accountLoginRequest, getUserInfo, getUserMenus } from "../../service/login/login"
import LocalCache from "@/utils/cache"
import router from "@/router"

import { menuMapToRoutes, menuMapToPermissions } from "@/utils/map-menu"

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: "",
      userInfo: {},
      userMenus: {},
      permissions: []
    }
  },
  getters: {},
  mutations: {
    saveToken(state, token) {
      state.token = token
    },
    saveUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    saveUserMenus(state, userMenus) {
      state.userMenus = userMenus

      // 3，获取对应的路由，注册路由，动态添加
      const routes = menuMapToRoutes(userMenus)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })

      // 4，获取用户的权限
      const permissions = menuMapToPermissions(userMenus)
      state.permissions = permissions
    }
  },
  actions: {
    async accountLoginAction({ commit, dispatch }, payload: IAccout) {
      // 用户登录
      const loginResult = await accountLoginRequest(payload)

      const { id, token } = loginResult.data
      commit('saveToken', token)
      LocalCache.setCache('token', token)
      // 获取用户信息
      const userInfo = await getUserInfo(id)
      commit("saveUserInfo", userInfo)
      LocalCache.setCache('userInfo', userInfo.data)

      // 获取用户菜单
      const userMenus = await getUserMenus(userInfo.data.id)
      commit("saveUserMenus", userMenus.data)
      LocalCache.setCache('userMenus', userMenus.data)

      router.push("/main/system/user")

    },
    // 保持用户刷新的数据
    loadLocalCache({ commit }) {
      const token = LocalCache.getCache("token")
      const userInfo = LocalCache.getCache("userInfo")
      const userMenus = LocalCache.getCache("userMenus")
      if (token) {
        commit("saveToken", token)
      }
      if (userInfo) {
        commit("saveUserInfo", userInfo)
      }
      if (userMenus) {
        commit("saveUserMenus", userMenus)
      }
    }
  },
}

export default loginModule